package my

import BaseViewModel
import LoadingStatus
import ObjectsRepository
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import my.models.ComponentUi
import my.models.ComputerUi
import my.models.MyObject
import my.models.MyObjectsEvent
import my.models.MyObjectsViewState

class MyObjectsViewModel(private val repository: ObjectsRepository) :
    BaseViewModel<MyObjectsViewState, MyObjectsEvent>(
        initialState = MyObjectsViewState()
    ) {

    override fun obtainEvent(event: MyObjectsEvent) {
        when (event) {
            MyObjectsEvent.LoadComponents -> if (viewState.components.isEmpty()) loadComponents()
            MyObjectsEvent.LoadComputers -> if (viewState.computers.isEmpty()) loadComputers()
            is MyObjectsEvent.SelectObject -> selectObject(event.obj)
        }
    }

    private fun loadComputers() {
        updateState { it.copy(loadingStatus = LoadingStatus.Loading) }
        viewModelScope.launch {
            repository.getMyComputers()
                .onSuccess { computers ->
                    updateState {
                        it.copy(
                            loadingStatus = LoadingStatus.Idle,
                            computers = computers.map { c -> ComputerUi.fromComputer(c) })
                    }
                }
                .onFailure { t ->
                    updateState { it.copy(loadingStatus = LoadingStatus.Error(t.message)) }
                }
        }
    }

    private fun loadComponents() {
        updateState { it.copy(loadingStatus = LoadingStatus.Loading) }
        viewModelScope.launch {
            repository.getMyComponents()
                .onSuccess { components ->
                    updateState {
                        it.copy(
                            loadingStatus = LoadingStatus.Idle,
                            components = components.map { c -> ComponentUi.fromComponent(c) })
                    }
                }
                .onFailure { t ->
                    updateState { it.copy(loadingStatus = LoadingStatus.Error(t.message)) }
                }
        }
    }

    private fun selectObject(obj: MyObject) {
        updateState { it.copy(selectedObject = obj) }
    }
}